<?php

namespace App\Http\Controllers\Api\JuHe;

use App\ChengYu;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Http\Request;

class ChengYuController extends Controller
{

    /**
     * 导入基础数据
     * @return [type] [description]
     */
    public function exportData()
    {
        $fileName = base_path('data_collect/cheng_yu.txt');
        // dd($fileName);
        $f    = fopen($fileName, 'r');
        $line = fgets($f);
        $data = [];
        while ($line) {
            // 100 行写入一次数据库
            array_push($data, [
                'cheng_yu' => trim($line),
            ]);
            $line = fgets($f);
            if ((count($data) > 100) || (!$line)) {
                $result = ChengYu::insert($data);
                $data   = [];
            }
        }
        echo "success";
    }

    /**
     * 定时任务获取数据
     * @return [type] [description]
     */
    public function cron()
    {
        $chengYu = $this->find();

        while ($chengYu) {

            $req = $this->requestChengYu($chengYu->cheng_yu);
            // if ($req['code'] == 500 || $req['code'] == ) {
            //     break;
            // }

          
                $chengYu = $this->find();
                if (!$chengYu) {
                    // 所有的成语已经处理完了
                    break;
                }
        

        }

        if ($chengYu) {
            $id = $chengYu->id;
        }

        $word = "平易近人";
        $this->requestChengYu($word);
    }

    /**
     * 请求接口
     * @param  [type] $word [description]
     * @return [type]       [description]
     */
    public function requestChengYu($word)
    {
        $chengYuBaseUrl = 'http://v.juhe.cn/chengyu/query';
        $data           = [
            'key'   => env('JU_HE_CHENG_YU_KEY'),
            'word'  => $word,
            'dtype' => 'json',
        ];
        $client   = new \GuzzleHttp\Client();
        $response = $client->request('POST', $chengYuBaseUrl, ['query' => $data]);
        if ($response->getStatusCode() != 200) {
            return $this->returnResponse(500, '网络请求错误');
        }
        $body = json_decode($response->getBody(), true);
        return $this->returnResponse($body['error_code'], $body['reason'], $body['result']);
    }

    /**
     * 处理数据
     * @param  string $word   [description]
     * @param  array  $result [description]
     * @return [type]         [description]
     */
    public function operate(string $word, array $result)
    {
        DB::beginTransaction();
        // 同义词
        $tongYiStatus = $this->insertAll($result['tongyi']);
        // 反义词
        $fanYiStatus = $this->insertAll($result['fanyi']);
        // 更新数据
        $updateStatus = $this->updateChengYu($word, $result);
        if ($tongYiStatus && $fanYiStatus && $updateStatus) {
            DB::commit();
            return true;
        } else {
            DB::rollBack();
            return false;
        }
    }

    /**
     * 更新成语解释
     * @param  string $chengYu [description]
     * @param  array  $result  [description]
     * @return [type]          [description]
     */
    public function updateChengYu(string $chengYu, array $result)
    {
        ChengYu::where([
            'cheng_yu' => $chengYu,
        ])->update([
            'bu_shou'       => $result['bushou'],
            'head'          => $result['head'],
            'pin_yin'       => $result['pinyin'],
            'cheng_yu_j_s'  => $result['chengyujs'],
            'from_'         => $result['from_'],
            'example'       => $result['example'],
            'yu_fa'         => $result['yufa'],
            'ci_yu_j_s'     => $result['ciyujs'],
            'yin_zheng_j_s' => $result['yinzhengjs'],
            'fan_yi'        => json_encode($result['fanyi']),
            'tong_yi'       => json_encode($result['tongyi']),
        ]);
    }

    /**
     * 插入新的成语
     * @param  array  $wordArr [description]
     * @return [type]          [description]
     */
    public function insertAll(array $wordArr)
    {
        foreach ($wordArr as $key => $value) {
            if (!ChengYu::where('cheng_yu', $value)->first()) {
                ChengYu::insert(['cheng_yu' => $value]);
            }
        }
    }

    /**
     * 查找需要解释的成语
     * @param  int|integer $id [description]
     * @return [type]          [description]
     */
    public function find(int $id = 0)
    {
        return ChengYu::where([
            ['is_operate', 1],
            ['id', '>', $id],
        ])->first();
    }

    /**
     * 格式化返回值
     * @param  int|integer $code [description]
     * @param  string      $msg  [description]
     * @param  array       $data [description]
     * @return [type]            [description]
     */
    public static function returnResponse(int $code = 0, string $msg = 'success', array $data = [])
    {
        return [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data,
        ];
    }

}
